<template>
  <div class="channel" v-loading="loading">
    <div class="top">
      <div class="search">
        <div class="contition">
          <div class="wrap_time">
            <date-time type="other" :query="query" @isFold="isShowFold"></date-time>
            <el-button type="primary" class="primary_btn fr find" v-on:click.stop="search">{{$t('public.search2')}}</el-button>
            <div class="clear"></div></div>
          <div class="wrap_drop">
            <unfold :isShow="isFold" :title="[]">
              <template slot="unfoldSlot">
                <div class="accs">
                  <span class="access">{{$t('report.imAccessId')}}：</span>
                  <el-select size="mini" v-model.trim="selectedAccessIdList" multiple filterable :placeholder="$t('report.searchByName')">
                    <el-option
                      v-for="item in accessIdOptions"
                      :label="item.label"
                      :value="item.value"
                      :key="item.value">
                    </el-option>
                  </el-select>
                </div>
              </template>
            </unfold>
          </div>
        </div>
      </div>
      <affix :label="$t('report.channelSurvey')"></affix>
      <div class="situation">
        <el-row>
          <el-col v-for="(item, index) in situation" :span="6" :key="index">
            <span class="sum_name">{{item.name}}</span>
            <span class="sit_num">{{item.value}}</span>
          </el-col>
        </el-row>
      </div>
      <affix :label="title"></affix>
    </div>
    <div :id="id">
      <el-row class="ichars">
        <highcharts :options="highchartsOptions"></highcharts>
       <div class="notes">
          <span class="light">{{$t('report.hicharsNotes')}}: <span></span>{{$t('report.hicharsLight')}}</span>
          <span class="dark"><span></span>{{$t('report.hicharsDark')}}</span>
        </div>
      </el-row>
      <div class="tab">
        <div class="export">

          <!-- <el-button class="primary_btn fr report_excel_btn"
            v-if="$store.getters.exportFromEnd && !isEcommerce"
            @click.stop="exportXls"
          >{{$t('report.exportXls')+($store.state.xlsxExportMode==='Both'?'(旧)':'')}}</el-button> -->

          <el-button class="primary_btn fr report_excel_btn"
            v-if="!isEcommerce"
            @click.stop="exportXlsx"
          >{{$t('report.exportXls')}}</el-button>

          <el-button class="primary_btn fr pdf" @click.stop="exportPdf">{{$t('report.exportPDF')}}</el-button>
          <el-button class="primary_btn fr pdf" v-on:click.stop="turnFromLook" v-show="!isEcommerce">
            <span v-show="!isAccess">接入号查看</span>
            <span  v-show="isAccess">渠道查看</span>
          </el-button>
        </div>
        <div class="deploy">
          <el-collapse accordion>
            <el-collapse-item>
              <template slot="title">
                <span class="fl explain">{{$t('report.toggleInstructe')}}</span>
              </template>
              <div>
                1. {{$t('report.imSessionAllNum')}} <br>
                2. {{$t('report.imAllEvaluateNum')}} <br>
                3. {{$t('report.participationRate')}} <br>
              </div>
            </el-collapse-item>
          </el-collapse>
        </div>
        <report-table :data="tableData" :sum="totalData" :config="headOptions.Config"></report-table>
      </div>
    </div>
    <el-dialog :close-on-click-modal="false" modal-append-to-body lock-scroll top="10%" :title="$t('report.reportExportHelp')" :visible.sync="dialogVisible" width="30%">
      <span>{{$t('report.reportExportTipTitle')}}</span>
      <span slot="footer" class="dialog-footer">
        <el-button class="primary_btn" @click="dialogVisible = false">{{$t('public.cancel')}}</el-button>
        <el-button class="primary_btn" type="primary" @click="confirm">{{$t('public.confirm')}}</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
  import unfold from '../../../ui-modules/unfold/index.vue'
  import affix from '../../../ui-modules/affix/Affix.vue'
  import dateTime from '../base/datetime.vue'
  import reportTable from '../base/reportTable.vue'
  import { deepClone, optionTimeTypeCheck } from '@/utils/m7Utils.js'
  import { exportReportPdf, headOptionsToXlsxHeaders, checkTime, searchTime, colorConfigArr } from '@/utils/reportUtils.js'
  import * as XlsxUtil from 'src/utils/XlsxUtil.umd.js'
  export default {
    name: 'im_report_csr_channel',
    data () {
      return {
        isAccess: false, // 是否为接入号查询
        isEcommerce: this.$store.getters.isEcommerce ? true : false,
        selectedAccessIdList: [], // 接入号绑定值
        isFold: false, // 是否展示搜索条件
        accessIdOptions: [], // 接入号数据
        situation: [], // 概况数据
        id: 'im_report_channel_csr',
        title: this.$t('report.imReportCsrChannel'),
        loading: false,
        query: {},
        dialogVisible: false,
        channelOptions: [], // 查询返回的渠道数据
        serverData: [], // 查询返回的数据
        headOptions: { Config: [], data: [] }, // 表头数据
        highchartsDefaultOptions: {
          chart: { type: 'column', animation: false },
          colors: colorConfigArr,
          xAxis: {
            categories: [],
            title: {
              enabled: true,
              text: '',
              style: { fontWeight: 'normal' }
            }
          },
          yAxis: {
            gridLineColor: '#e6e6e6',
            allowDecimals: false,
            title: { text: '' },
            showEmpty: false
          },
          title: { text: this.$t('report.imReportCsrChannel') },
          legend: { align: 'center', verticalAlign: 'top', y: 30 },
          tooltip: {
            // pointFormat: '<span style="color:{point.color}">\u25CF</span> {series.name}: <b>{point.y}{point.valueSuffix}</b><br/>',
            formatter: function () {
              var tip = '<span style="font-size:10px">' + this.x + '</span><br>'
              this.points.map((item, index) => {
                var unit = ''
                if (item.series.name.slice(-1) === '率') {
                  unit = '%'
                } else if (item.series.name.slice(-1) !== '率' && item.series.name.slice(-1) !== '数') {
                  unit = this.points[1].y > 0 ? `(${(item.y / this.points[1].y * 100).toFixed(1)}%)` : '(0%)'
                }
                tip += '<span style="color:' + item.series.color + '">\u25CF</span>' + item.series.name + ': <b>' +
                  item.y + '' + unit + '</b><br>'
              })
              return tip
            },
            shared: true
          },
          credits: { enabled: false },
          series: []
        }
      }
    },
    components: {
      affix,
      dateTime,
      unfold,
      reportTable
    },
    computed: {
      tableData () {
        return this.getTableData(this.serverData)
      },
      totalData () {
        this.situation = []
        if (!this.serverData || this.serverData.length === 0) {
          let headerConfig = this.headOptions.Config || []
          for (let i = 0; i < headerConfig.length; i++) {
            if (headerConfig[i].name !== 'channelName') {
              this.situation.push({name: headerConfig[i].displayname, value: 0})
            }
          }
          return [{channelName: this.$t('report.total')}]
        }

        let headerConfig = this.headOptions.Config || []
        let total = this.getTotalData(this.serverData, this.headOptions)[0]
        for (let i = 0; i < headerConfig.length; i++) {
          if (headerConfig[i].name !== 'channelName') {
            this.situation.push({name: headerConfig[i].displayname, value: total[headerConfig[i].name]})
          }
        }
        return [total]
      },
      highchartsOptions () {
        let options = deepClone(this.highchartsDefaultOptions)
        if (!this.serverData || this.serverData.length === 0) {
          return options
        }

        let headerConfig = this.headOptions.Config || []
        let datas = this.serverData
        let categoriesArray = []
        let seriesArray = []

        headerConfig.forEach(item => {
          if (!item.show) {
            return
          }
          if (item.name === 'channelName') {
            return
          }
          let serie = { name: item.displayname, data: [], valueName: item.name }
          if (item.name === 'appraiseRate') {
            serie.tooltip = { valueSuffix: '%' }
          }
          seriesArray.push(serie)
        })

        for (let i = 0; i < datas.length; i++) {
          if (!this.isAccess) {
            categoriesArray.push(this.getChannelName(datas[i].channel))
          } else {
            categoriesArray.push(this.getAccessName(datas[i]._id))
          }
          for (let j = 0; j < seriesArray.length; j++) {
            seriesArray[j].data.push(parseFloat(datas[i][seriesArray[j].valueName]))
          }
        }

        options.xAxis.categories = categoriesArray
        options.series = seriesArray

        return options
      }
    },
    methods: {
      // 切换查询方式
      turnFromLook () {
        this.isAccess = !this.isAccess
        this.search()
      },
      getTableData (serverData) {
        if (!serverData || serverData.length === 0) {
          return []
        }

        let data = deepClone(serverData)
        data.forEach(item => {
          if (!this.isAccess) {
            item.channelName = this.getChannelName(item.channel)
          } else {
            item.channelName = this.getAccessName(item._id)
          }
          item.appraiseRate = `${item.appraiseRate}%`
          for (let key in item) {
            if (key !== 'channelName' && key !== 'sessionCount' && key !== 'totalAppraiseCount' && key !== 'channel' && key !== 'appraiseRate') {
              item[key] = item.totalAppraiseCount > 0 ? `${item[key]}(` + (item[key] * 100 / item.totalAppraiseCount).toFixed(1) + '%)' : `${item[key]}(0.0%)`
            }
          }
        })

        return data
      },
      getTotalData (serverData, headOptions) {
        let headerConfig = headOptions.Config || []
        let datas = serverData
        let total = {
          channelName: this.$t('report.total'),
          totalAppraiseCount: 0,
          sessionCount: 0
        }

        for (let i = 0; i < headerConfig.length; i++) {
          for (let j = 0; j < datas.length; j++) {
            if (!isNaN(datas[j][headerConfig[i].name])) {
              if ((headerConfig[i].name in total) === false) {
                total[headerConfig[i].name] = 0
              }
              total[headerConfig[i].name] += datas[j][headerConfig[i].name]
            }
          }
        }

        // 参评率
        total.appraiseRate = total.sessionCount > 0 ? ((total.totalAppraiseCount / total.sessionCount) * 100).toFixed(1) : '0.0'
        total.appraiseRate = `${total.appraiseRate}%`
        // 不同评价的概率
        for (let key in total) {
          if (key !== 'channelName' && key !== 'sessionCount' && key !== 'totalAppraiseCount' && key !== 'agentId' && key !== 'appraiseRate') {
            total[key] = total.totalAppraiseCount > 0 ? `${total[key]}(` + (total[key] * 100 / total.totalAppraiseCount).toFixed(1) + '%)' : `${total[key]}(0.0%)`
          }
        }
        return [total]
      },
      isShowFold (bool) {
        this.isFold = bool
      },
      getAccessName (id) {
        for (let i = 0; i < this.accessIdOptions.length; i++) {
          if (this.accessIdOptions[i].value === id) {
            return this.accessIdOptions[i].name
          }
        }
        return this.$t('report.imReportDeletedAccess')
      },
      getChannelName (id) {
        for (let i = 0; i < this.channelOptions.length; i++) {
          if (this.channelOptions[i].channel === id) {
            return this.channelOptions[i].channelName
          }
        }
        return ''
      },
      getSearchQueryData () {
        let data = {
          reportType: this.id,
          account: this.$store.state.session.user.account,
          query: { reportType: this.id },
          user: {
            type: this.$store.state.session.user.type,
            moduleUsers: this.$store.state.session.user.moduleUsers
          }
        }
        let query = deepClone(this.query)
        if (query.timeType === 'other') {
          // 校验类型与时间
          let message = checkTime(query.StartTime, query.EndTime, false, true)
          if (message !== true) {
            this.$message.error(this.$t(message))
            return
          }
        }
        if (this.selectedAccessIdList.length > 0) {
          query.selectedAccessIdList = this.selectedAccessIdList.join(',')
        }
        data.query = Object.assign({}, data.query, query)
        if (this.isAccess) {
          data.query.isAccessId = true
        }
        return data
      },
      search () {
        var queryData = this.getSearchQueryData()

        if (!queryData) {
          return
        }

        this.loading = true
        let promis = null
        this.$store.dispatch('queryImChannelCsrReport', queryData).then((res) => {
          if (this.$store.state.report.customExportData) {
            res = JSON.parse(this.$store.state.report.customExportData)
          }
          // 表头
          this.headOptions = optionTimeTypeCheck(deepClone(res.tableHeader) || this.headOptions)

          this.channelOptions = deepClone(res.channels) || this.channelOptions
          this.serverData = deepClone(res.data) || this.serverData
          this.loading = false
        })
      },
      // 处理导出数据
      dealExportData (res) {
        this.loading = false
        var headOptions = optionTimeTypeCheck(deepClone(res.tableHeader) || [])
        var serverData = deepClone(res.data) || []
        var sum = []
        if (serverData.length !== 0) {
          sum = this.getTotalData(serverData, headOptions)
        }
        var tableData = this.getTableData(serverData).concat(sum)
        var headers = headOptionsToXlsxHeaders(headOptions.Config)

        var dh = XlsxUtil.getDownloadHelper(headers, tableData)
        var timeStamp = XlsxUtil.dateFormat(new Date(), 'yyyy-MM-dd hh-mm-ss')
        dh.download(this.$t('report.imReportCsrChannel') + timeStamp)
      },
      // 前端导出
      exportXlsx () {
        var queryData = this.getSearchQueryData()

        if (!queryData) {
          return
        }

        this.loading = true
        this.$store.dispatch('queryImChannelCsrReport', queryData).then((res) => {
          if (this.$store.state.report.customExportData) {
            res = JSON.parse(this.$store.state.report.customExportData)
          }
          this.dealExportData(res)
        })
      },
      exportXls () {
        let data = {
          Method: 'exportImChannelCSR',
          Query: { reportType: this.id, user: this.$store.state.session.user._id }
        }
        let query = deepClone(this.query)
        if (query.timeType === 'other_half_hour') {
          let message = checkTime(query.StartTime, query.EndTime, true, false) // 校验类型与时间
          if (message !== true) {
            this.$message.error(this.$t(message))
            return
          }
        }
        if (this.selectedAccessIdList.length > 0) {
          query.selectedAccessIdList = this.selectedAccessIdList.join(',')
        }
        data.Query = Object.assign({}, data.Query, query)
        this.$store.dispatch('exportImChannelCsrReport', data)
      },
      exportPdf () {
        this.dialogVisible = true
      },
      confirm () {
        this.dialogVisible = false
        exportReportPdf({title: this.$t('report.webchat') + this.$t('report.imReportCsrChannel') + searchTime(this.query), id: this.id})
      }
    },
    beforeMount () {
      let type = this.isEcommerce ? 'ecommerceAccessId' : 'accessIds'
      this.$store.dispatch('getCache', { type: type }).then(accessIds => {
        this.accessIdOptions = accessIds.map(accessId => ({ label: `${accessId.name}[${accessId.platform}]`, name: accessId.name, platform: accessId.platform, value: accessId._id }))
        this.search()
      })
    }
  }
</script>
<style lang="stylus" scoped>
  @import "../../../../assets/common.styl"
  .channel
    .accs
      margin 14px 0 0px 0px
      .access
        margin-right 10px
      .el-select
        width 600px
    .tab
      .deploy
        .tip
          margin-left 0px
</style>
